import axios from "axios";
import { getToken, removeToken, setToken } from "@/utils/token";
import { ElMessage } from "element-plus";

const request = axios.create({
  baseURL: 'https://m1.apifoxmock.com/m1/7043257-6763262-default/',
  timeout: 5000,
});

// 添加请求拦截器
request.interceptors.request.use(function (config){
    const token = getToken();
    try{
        config.headers['token'] = encodeURIComponent(token);
    } catch(e){
        console.error('Token encoding error:', e);
        config.headers['token'] = btoa(unescape(encodeURIComponent(token)));
    }
    //发送请求之前做些什么
    // console.log('config: ',config);
    return config;
},function (error){
    //对请求错误做些什么
    if(error.response.status === 404 & error.response){
        ElMessage.error('请求接口不存在！');
    }
    else if(error.response.status === 401){
        ElMessage.error('请先重新登录！');
        removeToken();
        window.location.reload()
    }
    else{
        ElMessage.error('请求异常，请检查服务器状态!');
    }
    return Promise.reject(error);  
})

// 添加响应拦截器
request.interceptors.response.use(function (response){
    //对响应数据做些什么
    return response.data;
},function (error){
    //对响应错误做些什么
    console.log('error: ',error);
    return Promise.reject(error);
})

export const post = (obj) => {
    obj.method = 'POST'; 
    return request(obj)
};

export const get = (obj) => {
    obj.method = 'GET'; 
    if(obj.data){
        // obj.url += '?' + Object.keys(obj.data).map(key => `${key}=${obj.data[key]}`).join('&')
        obj.params = obj.data
        return obj.data
    }
    return request(obj)
};